import router, { asyncRoutes } from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { Route } from 'vue-router'
import { PermissionModule } from '@/store/modules/permission'
import { UserModule } from '@/store/modules/user'
import settings from './settings'
import { getStore } from '@/utils/store'
import { getToken } from '@/utils/cookies'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

const getPageTitle = (key: string) => {
  /* const hasKey = i18n.te(`route.${key}`)
  if (hasKey) {
    const pageName = i18n.t(`route.${key}`)
    return `${pageName} - ${settings.title}`
  } */
  return `${settings.title}`
}

// router.addRoutes(asyncRoutes)

router.beforeEach((to, _, next) => {
  // Start progress bar
  NProgress.start()
  if (whiteList.indexOf(to.path.toLowerCase()) !== -1) {
    next()
    return
  }
  console.log('permission.ts ->', to.path)
  console.log(UserModule.access_token)
  const token = getStore({ name: 'access_token' })
  // debugger
  if (token) {
    if (to.path.toLowerCase() === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        const hasRoles: boolean = !!UserModule.roles && UserModule.roles.length > 0
        console.log('hasRoles -> ', hasRoles)
        console.log('Roles ->', UserModule.roles)
        if (!hasRoles) {
          UserModule.GetUserInfo().then(() => {
            return PermissionModule.GenerateRoutes(UserModule.roles)
          }).then(() => {
            // next({...to, replace: true})
            next()
          }) // 获取用户详情
        } else {
          next()
        }
      } catch (error) {
        // remove token and go to login page to re-login
        if (top.location !== location) {
          Message.error(error || 'Has Error')
        } else {
          UserModule.FedLogOut().then(_ => {
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          })
        }
      }
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path.toLowerCase()) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to: Route) => {
  // Finish progress bar
  NProgress.done()

  // set page title
  document.title = getPageTitle(to.meta.title)
})
